import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../config/app_colors.dart';
import '../../utils/currency_manager.dart';

/// 货币选择顶部面板
class CurrencySelectorPanel extends StatefulWidget {
  final CurrencyModel? initialCurrency;
  final Function(CurrencyModel)? onCurrencySelected;
  final VoidCallback? onClose;

  const CurrencySelectorPanel({
    Key? key,
    this.initialCurrency,
    this.onCurrencySelected,
    this.onClose,
  }) : super(key: key);

  @override
  State<CurrencySelectorPanel> createState() => _CurrencySelectorPanelState();
}

class _CurrencySelectorPanelState extends State<CurrencySelectorPanel>
    with SingleTickerProviderStateMixin {
  CurrencyModel? _selectedCurrency;
  late AnimationController _animationController;
  late Animation<Offset> _slideAnimation;

  @override
  void initState() {
    super.initState();
    _selectedCurrency = widget.initialCurrency ?? CurrencyManager.instance.currentCurrency;
    
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );
    
    _slideAnimation = Tween<Offset>(
      begin: const Offset(0, -1),
      end: Offset.zero,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Curves.easeInOut,
    ));
    
    _animationController.forward();
  }
  
  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }
  
  void _closePanel() async {
    await _animationController.reverse();
    widget.onClose?.call();
  }

  @override
  Widget build(BuildContext context) {
    return SlideTransition(
      position: _slideAnimation,
      child: Container(
        width: double.infinity,
        decoration: BoxDecoration(
          color: AppColors.background,
          borderRadius: BorderRadius.only(
            bottomLeft: Radius.circular(20.r),
            bottomRight: Radius.circular(20.r),
          ),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              blurRadius: 10,
              offset: const Offset(0, 5),
            ),
          ],
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 安全区域顶部间距
            SizedBox(height: MediaQuery.of(context).padding.top),
            
            // 标题栏
            Container(
              padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 15.h),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    'Currency',
                    style: TextStyle(
                      fontSize: 20.sp,
                      fontWeight: FontWeight.bold,
                      color: AppColors.textPrimary,
                    ),
                  ),
                  GestureDetector(
                    onTap: _closePanel,
                    child: Container(
                      padding: EdgeInsets.all(8.w),
                      decoration: BoxDecoration(
                        color: AppColors.backgroundSecondary,
                        borderRadius: BorderRadius.circular(20.r),
                      ),
                      child: Icon(
                        Icons.close,
                        size: 20.sp,
                        color: AppColors.textSecondary,
                      ),
                    ),
                  ),
                ],
              ),
            ),
            
            // 货币选项网格
            Container(
              padding: EdgeInsets.symmetric(horizontal: 20.w),
              child: GridView.builder(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 3,
                  crossAxisSpacing: 12.w,
                  mainAxisSpacing: 12.h,
                  childAspectRatio: 2.5,
                ),
                itemCount: CurrencyManager.supportedCurrencies.length,
                itemBuilder: (context, index) {
                  final currency = CurrencyManager.supportedCurrencies[index];
                  final isSelected = _selectedCurrency?.code == currency.code;
                  
                  return GestureDetector(
                    onTap: () {
                      setState(() {
                        _selectedCurrency = currency;
                      });
                    },
                    child: Container(
                      decoration: BoxDecoration(
                        color: isSelected ? AppColors.primaryVariant : AppColors.backgroundSecondary,
                        borderRadius: BorderRadius.circular(12.r),
                        border: Border.all(
                          color: isSelected ? AppColors.primaryVariant : AppColors.border,
                          width: 1.5,
                        ),
                      ),
                      child: Center(
                        child: Text(
                          '${currency.code} ${currency.symbol}',
                          style: TextStyle(
                            fontSize: 14.sp,
                            fontWeight: FontWeight.w600,
                            color: isSelected ? AppColors.textWhite : AppColors.textPrimary,
                          ),
                        ),
                      ),
                    ),
                  );
                },
              ),
            ),
            
            SizedBox(height: 20.h),
            
            // 确认按钮
            Container(
              padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 20.h),
              width: double.infinity,
              child: ElevatedButton(
                onPressed: () {
                  if (_selectedCurrency != null) {
                    widget.onCurrencySelected?.call(_selectedCurrency!);
                    _closePanel();
                  }
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: AppColors.primaryVariant,
                  foregroundColor: AppColors.textWhite,
                  padding: EdgeInsets.symmetric(vertical: 16.h),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12.r),
                  ),
                  elevation: 0,
                ),
                child: Text(
                  'Confirm',
                  style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

/// 显示货币选择面板的便捷方法
class CurrencyDialogHelper {
  static OverlayEntry? _overlayEntry;
  
  static void showCurrencySelector(
    BuildContext context, {
    CurrencyModel? initialCurrency,
    Function(CurrencyModel)? onCurrencySelected,
  }) {
    if (_overlayEntry != null) {
      return; // 防止重复显示
    }
    
    _overlayEntry = OverlayEntry(
      builder: (context) => Material(
        color: Colors.black.withOpacity(0.3),
        child: GestureDetector(
          onTap: () => _closeCurrencySelector(),
          child: Container(
            alignment: Alignment.topCenter,
            child: GestureDetector(
              onTap: () {}, // 防止点击面板时关闭
              child: CurrencySelectorPanel(
                initialCurrency: initialCurrency,
                onCurrencySelected: (currency) {
                  onCurrencySelected?.call(currency);
                  _closeCurrencySelector();
                },
                onClose: _closeCurrencySelector,
              ),
            ),
          ),
        ),
      ),
    );
    
    Overlay.of(context).insert(_overlayEntry!);
  }
  
  static void _closeCurrencySelector() {
    _overlayEntry?.remove();
    _overlayEntry = null;
  }
}